package org.iartisan.thought.server.service.support;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.iartisan.thought.server.dbm.model.CustBaseDO;
import org.iartisan.thought.server.dbm.model.TopicDO;
import org.iartisan.thought.server.service.bo.CustBO;
import org.iartisan.thought.server.service.bo.UserMessageBO;
import org.iartisan.thought.server.service.management.UserMessageManagementService;
import org.iartisan.thought.server.service.query.CustQueryService;
import org.iartisan.thought.server.service.query.TopicQueryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 消息处理
 *
 * @author King
 * @since 2018/2/1
 */
@Service
public class MessageHandler {

    @Autowired
    private Configuration configuration;

    private static Template welcomeTemplate;

    private static Template commentTemplate;

    private static final String welcome_msg_location = "welcome_msg.ftl";

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserMessageManagementService userMessageManagementService;

    private Template getWelcomeTemplate() throws IOException {
        if (null == welcomeTemplate) {
            welcomeTemplate = configuration.getTemplate(welcome_msg_location);
        }
        return welcomeTemplate;
    }

    private Template getCommentTemplate() throws IOException {
        if (null == commentTemplate) {
            commentTemplate = configuration.getTemplate("comment.ftl");
        }
        return commentTemplate;
    }

    private Template getReplyTemplate() throws IOException {
        if (null == commentTemplate) {
            commentTemplate = configuration.getTemplate("reply.ftl");
        }
        return commentTemplate;
    }

    /**
     * 欢迎消息
     */
    public void sendWelcomeMsg(String userId) {
        StringWriter writer = new StringWriter();
        try {
            getWelcomeTemplate().process(null, writer);
            String message = writer.toString();
            UserMessageBO messageBO = new UserMessageBO();
            messageBO.setContent(message);
            messageBO.setFromUser("system");
            messageBO.setToUser(userId);
            userMessageManagementService.saveData(messageBO);
        } catch (Exception e) {
            logger.error("sendWelcomeMsg", e);
        }
    }

    @Autowired
    private TopicQueryService topicQueryService;

    /**
     * 贴子回复消息
     */
    public void sendCommentMsg(String topicId, String commentId, String replyId) {
        StringWriter writer = new StringWriter();
        try {
            TopicDO topicDO = topicQueryService.getTopicByTopicId(topicId);
            CustBO custBO = custQueryService.getCustInfoById(replyId);
            if (!topicDO.getCustomerId().equals(custBO.getCustId())) {
                Map<String, Object> dataModel = new HashMap<>();
                dataModel.put("replyName", custBO.getCustUserName());
                dataModel.put("replyId", custBO.getCustId());
                dataModel.put("title", topicDO.getTitle());
                dataModel.put("url", "/topic/query/queryDetailData/" + topicId + "#" + commentId);
                getCommentTemplate().process(dataModel, writer);
                String message = writer.toString();
                UserMessageBO messageBO = new UserMessageBO();
                messageBO.setContent(message);
                messageBO.setFromUser("system");
                messageBO.setToUser(topicDO.getCustomerId());
                userMessageManagementService.saveData(messageBO);
            }
        } catch (Exception e) {
            logger.error("sendCommentMsg", e);
        }
    }

    @Autowired
    private CustQueryService custQueryService;

    /**
     * 在贴子中对其它人进行回复
     *
     * @param topicId
     * @param commentId
     * @param custId    被回复人
     * @param replyName 回复人姓名
     */
    public void sendReplyMsg(String topicId, String commentId, String custId, String replyName) {
        StringWriter writer = new StringWriter();
        try {
            TopicDO topicDO = topicQueryService.getTopicByTopicId(topicId);
            CustBaseDO custBaseDO = custQueryService.getCustIdByUserName(replyName);
            CustBO beReply = custQueryService.getCustInfoById(custId);
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("replyName", beReply.getCustUserName());
            dataModel.put("replyId", beReply.getCustId());
            dataModel.put("title", topicDO.getTitle());
            dataModel.put("url", "/topic/query/queryDetailData/" + topicId + "#" + commentId);
            getReplyTemplate().process(dataModel, writer);
            String message = writer.toString();
            UserMessageBO messageBO = new UserMessageBO();
            messageBO.setContent(message);
            messageBO.setFromUser("system");
            messageBO.setToUser(custBaseDO.getCustId());
            userMessageManagementService.saveData(messageBO);
        } catch (Exception e) {
            logger.error("sendCommentMsg", e);
        }
    }
}
